//
//  DataProcessing.m
//  KidReading
//
//  Created by telen on 14/12/8.
//  Copyright (c) 2014年 刘赞黄Telen. All rights reserved.
//

#import "DataProcessing.h"
#import "ConstDefine.h"
#import "JRReachability.h"
#import <sys/utsname.h>
//#import "DataProcessing+JRIAP.h"

@implementation DataProcessing
{
    BOOL isForChinese;
    //
    NSThread* thread;
    NSMutableArray* mSoundConvertQue;
    NSMutableArray* soundConvertDelegateArr;
    //
    //NSNotification* tempNotice_pay;
}

static DataProcessing* dataProcessingSingle = nil;
+(DataProcessing *)shareSingle
{
    if (!dataProcessingSingle) {
        dataProcessingSingle = [[DataProcessing alloc] init];
//        [[NSNotificationCenter defaultCenter] addObserver:dataProcessingSingle selector:@selector(receiveNotification_pop:) name:@"pop" object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:dataProcessingSingle selector:@selector(receiveNotification_payvip:) name:@"payvip" object:nil];
    }
    return dataProcessingSingle;
}



//- (void)payContinue
//{
//    [self receiveNotification_payvip:tempNotice_pay];
//}

+ (NSDate *)dateFromtimestamp:(long long)timestamp
{
    return [NSDate dateWithTimeIntervalSince1970:timestamp*0.001];
}

+ (long long)timestampFromNSDate:(NSDate *)date
{
    if (date) {
        long long timestamp = [date timeIntervalSince1970] * 1000;
        return timestamp;
    }
    return 0;
}

+ (long long)timestampFromNSDate_second:(NSDate *)date
{
    if (date) {
        long long timestamp = [date timeIntervalSince1970];
        return timestamp * 1000;
    }
    return 0;
}

+ (long long)timestampFromtimestamp_tilDayEnd:(long long)timestamp
{
    LongLong end = timestamp;
    NSTimeInterval vipend = end/1000;
    NSDate* vipTimeEnd = [NSDate dateWithTimeIntervalSince1970:vipend];
    NSString* _vipTimeEnd = [vipTimeEnd stringWithFormat:[NSDate dateFormatString]];
    _vipTimeEnd = [_vipTimeEnd stringByAppendingString:@" 23:59:59"];
    NSDate* endDate = [NSDate dateFromString:_vipTimeEnd];
    return [self timestampFromNSDate:endDate];
}

+ (NSDate *)dateFromNSDate_tilDayEnd:(NSDate *)date
{
    LongLong end = [self timestampFromNSDate:date];
    NSTimeInterval vipend = end/1000;
    NSDate* vipTimeEnd = [NSDate dateWithTimeIntervalSince1970:vipend];
    NSString* _vipTimeEnd = [vipTimeEnd stringWithFormat:[NSDate dateFormatString]];
    _vipTimeEnd = [_vipTimeEnd stringByAppendingString:@" 23:59:59"];
    return [NSDate dateFromString:_vipTimeEnd];
}

+ (long long)timestampFromNSDate_tilDayEnd:(NSDate *)date
{
    LongLong end = [self timestampFromNSDate:date];
    return [self timestampFromtimestamp_tilDayEnd:end];
}

//- (void)receiveNotification_payvip:(NSNotification*)noti
//{
//#ifndef WHY_PJ
//    if (!noti) {
//        return;
//    }
////    if ([CacheData shareSingle].isLastLoginFromDevice && ![CacheData shareSingle].isLockedDeviceLogin) {
//    self.isRetailNow = @"no";
//    if([WY3SDKLogin currentUser].exist && [[WY3SDKLogin currentUser] isTouristAcount] && ![CacheData shareSingle].isLockedDeviceLogin){
//        [[RootViewController shareLastInstance] showAlertMsgMustBuyVIP_LockChoose];
//        tempNotice_pay = noti;
//        return;
//    }
//    //
//    NSDictionary* dict = [noti userInfo];
//    PopBaseViewController* currentVC = noti.object;
//    if (![currentVC isKindOfClass:[PopBaseViewController class]]) {
//        currentVC = nil;
//    }
//    if (dict && currentVC) {
//        NSString* pid = [dict objectForKey:@"pid"];
//        NSString* msg = [dict objectForKey:@"msg"];
//        NSString* pids = [dict objectForKey:@"pids"];
//        NSArray* arr = [pids componentsSeparatedByString:@","];
//        if (pid) {
//            [self payPrductID:pid pids:arr presentVC:currentVC successMsg:msg.URLDecodedString];
//        }else{
//            [UIAlertView showAluertMessage:@"BuyVip Error pid" title:nil sureBtn:@"sure"];
//        }
//    }
//#endif
//}

////从IAPHelper callback
//+ (BOOL)recordPaymentTransaction_Ser2:(SKPaymentTransaction*) trans
//{
//    NSString *productIdentifier = trans.payment.productIdentifier;
//    NSString *orderid = trans.transactionIdentifier;
//    if (!productIdentifier || !orderid) {
//        [[DataProcessing shareSingle] saveBackUpIsRetail:@""];
//        return YES;
//    }
//    //[[IAPShare sharedHelper].iap provideContent:productIdentifier];
//    //NSLog(@"SUCCESS %@",response);
//    // Telen 添加向服务器验证，同步
//    // 验证凭据，获取到苹果返回的交易凭据
//    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
//    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
//    // 从沙盒中获取到购买凭据
//    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
//    if (receiptData) {
//        NSString* receiptStr = [receiptData base64EncodedString];
//        NSString* url = [__Ser3_0_URL_Base_ stringByAppendingPathComponent:__URL_PortBuyJSP_trans];
//        NSMutableDictionary* mdict = [NSMutableDictionary new];
//        [mdict setObject:productIdentifier forKey:@"purchase_type"];
//        [mdict setObject:orderid forKey:@"transaction_id"];
//        [mdict setObject:receiptStr forKey:@"receipt"];
//        NSString *uuid = [[DataProcessing shareSingle] getUMSuiid];
//        [mdict setObject:uuid forKey:@"uuid"];
//        if (![IAPShare sharedHelper].iap.production) {
//            [mdict setObject:@"sandbox" forKey:@"iap_endpoint"];
//        }
//        mdict = [[NetRequest shareSingle] netRequestAddBaseInfo:mdict];
//        NSString* postStr = [[NetRequest shareSingle] netPostString_fromDict:mdict];
//        NSData* data = [NSData dataWithBytes:postStr.UTF8String length:postStr.length];
//        NSDictionary* retDict = [[NetRequest shareSingle] sendSynchronous:url ref:nil data:data];
//        //
//        
//        //外层解析
//        NSDictionary* retInfo = nil;
//        if (retDict) {
//            NSDictionary* dict = retDict[@"retinfo"];
//            NSString* msg = retDict[@"msg"];
//            NSInteger flag = [retDict[@"flag"] integerValue];
//            if (msg) {
//                [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
//                if (flag == 1001) {//token 过期
//#ifndef WHY_PJ
//                    [[DBHelper shareInstance] showTokenOutMsg:msg];
//#endif
//                    return NO;
//                }
//            }
//            if (flag == 1) {
//                retInfo = dict;
//            }
//        }
//        //
//        if(!retInfo){
//            [DataProcessing do_Main_quick:^{
//                [[DataProcessing shareSingle] saveBackUpIsRetail:@""];
//                //[[WaitingShow shareSingleShow] showString:@"Net Return Null" andAutoHide:YES];
//                NSString *str = @"buyfailvip";
//                [UIAlertView showAluertMessage:NSLocalizedString(str, "") title:nil sureBtn:NSLocalizedString(@"sure", "")];
//#if __Debug_Net_Error
//                [PopWebView popWebViewWithData:data withURL:@"nil"];
//#endif
//            }];
//        }else{
//            NSNumber* purchaseStat = retInfo[@"purchaseStat"];
//            //1订单成功 2失败且不需要删除 3失败且需要删除
//            if (purchaseStat) {
//                if ([purchaseStat intValue] == 1) {
//                    
//                    NSDictionary* udict = retInfo[@"user"];
//                    if (udict) {
//                        UserInfo* uinfo = [UserInfo objectWithKeyValues:udict];
//                        uinfo.shelfs = udict[@"bsIds"];
//                        uinfo.banners = udict[@"bannerIds"];
//                        UserInfo* uinfo_old = [CacheData shareSingle].getUserLoginInfo;
//                        if (uinfo_old.uid == uinfo.uid) {
//                            uinfo.country_code = uinfo_old.country_code;
//                            uinfo.catoken = uinfo_old.catoken;
//                        }else if([WY3SDKLogin currentUser].uid == uinfo.uid){
//                            uinfo.country_code = [WY3SDKLogin currentUser].area;
//                            uinfo.catoken = [WY3SDKLogin currentUser].token;
//                        }
//                        [[CacheData shareSingle] saveUserLoginInfo:uinfo];
//#ifndef WHY_PJ
//                        [[DBHelper shareInstance] updateListToTableClass:NSStringFromClass([TABLE_USERS class]) dictArr:@[udict] complete:^{
//                        }];
//#endif
//                        dispatch_async( dispatch_get_main_queue(), ^{
//                            [[NSNotificationCenter defaultCenter] postNotificationName:@"VIPInfoUpdate" object:nil];
//                        });
//                        //置空isretail
//                        [[DataProcessing shareSingle] saveBackUpIsRetail:@""];
//                        return YES;
//                    }
//                }
//                if ([purchaseStat intValue] == 3) {
//                    //置空isretail
//                    [[DataProcessing shareSingle] saveBackUpIsRetail:@""];
//                    return YES;
//                }
//            }
//            return NO;
//        }
//    }
//    return NO;
//}

//从IAPHelper callback
+ (BOOL)recordPaymentTransaction:(SKPaymentTransaction*) trans
{
    //return [self recordPaymentTransaction_Ser2:trans];
    return YES;
}

//#ifndef WHY_PJ
//- (void)payPrductID:(NSString*)pid pids:(NSArray*)pids presentVC:(PopBaseViewController*)vc successMsg:(NSString*)msg
//{
//    if ([IAPShare sharedHelper].isBuying) {
////        NSLog(@"Is the transaction，Please Wait a minutes!");
//        return;
//    }
////    NSLog(@"Is the transaction，Ing!");
//    NSSet* dataSet = [[NSSet alloc] initWithArray:@[pid]];
//    if(![IAPShare sharedHelper].iap) {
//        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
//    }else{
//        [IAPShare sharedHelper].iap.productIdentifiers = dataSet;
//    }
//    
//#if __PaySandBox
//    [IAPShare sharedHelper].iap.production = NO;
//#else
//    [IAPShare sharedHelper].iap.production = YES;
//#endif
//    //block
//    void(^buyCompletion)(SKPaymentTransaction* trans) = ^(SKPaymentTransaction* trans){
//        [IAPShare sharedHelper].isBuying = NO;
//        [IAPShare sharedHelper].msg = nil;
//        
//        if(trans.error)
//        {
//            [[WaitingShow shareSingleShow] showString:trans.error.localizedDescription andAutoHide:YES];
//            NSLog(@"Buy Fail %@",[trans.error localizedDescription]);
//        }
//        else if(trans.transactionState == SKPaymentTransactionStatePurchased) {
//        }
//        else if(trans.transactionState == SKPaymentTransactionStateFailed) {
//            NSLog(@"Buy Fail");
//        }
//    };
//    
//    [IAPShare sharedHelper].isBuying = YES;
//    [IAPShare sharedHelper].msg = msg;
//    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest* request,SKProductsResponse* response)
//     {
//         if(response > 0 ) {
//              [[DataProcessing shareSingle] saveIsRetail];
//             for (SKProduct* product in [IAPShare sharedHelper].iap.products) {
//                 if ([product.productIdentifier isEqualToString:pid]) {
//                     [[IAPShare sharedHelper].iap buyProduct:product onCompletion:buyCompletion];
//                     break;
//                 }
//             }
//         }else{
//             [IAPShare sharedHelper].isBuying = NO;
//             [IAPShare sharedHelper].msg = nil;
//             [UIAlertView showAluertMessage:NSLocalizedString(@"buyfailvip", "") title:nil sureBtn:NSLocalizedString(@"sure", "")];
//         }
//     }];
//}
//#endif

//+ (NSString *)getBuyUrl
//{
//    NSString* url = [__Ser3_0_URL_Base_ stringByAppendingString:__URL_PortBuyJSP_];
//    NSDictionary* dict = [[NetRequest shareSingle] netRequestAddBaseInfo:@{}];
//    return [[NetRequest shareSingle] netFullUrl_Get:url fromDict:dict];
//}


+ (NSString *)chooseLanguageFromCN:(NSString *)chinese andEN:(NSString *)english
{
    if ([[self shareSingle] isChineseForLocalSystem]) {
        if (chinese) {
            return chinese;
        }else{
            return nil;
        }
    }else{
        if (english) {
            return english;
        }else{
            return nil;
        }
    }
    return nil;
}

+ (NSString*)languageForfileName:(NSString*)name
{
    if ([[self shareSingle] isChineseForLocalSystem]) {
        NSMutableArray* arr = [NSMutableArray arrayWithArray:[name componentsSeparatedByString:@"."]];
        if (arr.count < 2) {
            return name;
        }else{
            NSString* str1 = [arr lastObject];
            [arr removeObject:str1];
            NSString* str2 = [arr lastObject];
            [arr removeObject:str2];
            str2 = [str2 stringByAppendingString:@"_cn"];
            [arr addObject:str2];
            [arr addObject:str1];
            name = [arr componentsJoinedByString:@"."];
        }
    }
    return name;
}

+ (NSString*)full_BaseUrl:(NSString*)baseUrl url:(NSString*)url
{
    if (![url hasPrefix:@"http"]) {
        NSArray* arr = [baseUrl componentsSeparatedByString:@"://"];
        if (arr.count < 2) {
            NSLog(@"BaseURL 不正确 %@",baseUrl);
            return nil;
        }
        NSString* lastUrl = [arr lastObject];
        url = [lastUrl stringByAppendingPathComponent:url];
        url = [baseUrl stringByReplacingOccurrencesOfString:lastUrl withString:url];
    }
    return url;
}

+ (NSString*)fullTalkZipFileUrl:(NSString*)url{
    return [self full_BaseUrl:[DataProcessing shareSingle].talk_file_url url:url];
}
+ (NSString*)fullTalkVideoFileUrl:(NSString*)url{
    return [self full_BaseUrl:[DataProcessing shareSingle].talk_file_url url:url];
}

+ (NSString*)fullWordDictUrl:(NSString*)url{
    return [self full_BaseUrl:[DataProcessing shareSingle].word_dict_url url:[NSString stringWithFormat:@"%@.html",url]];
}

+ (NSString*)fullWordDictUrl:(NSString*)url ContainMp3Path:(NSString*)path{
    NSString* wordPath = [DataProcessing fullWordDictUrl:url];
    return [NSString stringWithFormat:@"%@?py=%@",wordPath,path];
}

+ (NSString*)fullFlowBookHtmlUrl:(NSString*)url{
    return [self full_BaseUrl:[DataProcessing shareSingle].flowBook_host url:url];
}

+ (NSString*)fullFrevalDataUrl:(NSString*)url{
    return [self full_BaseUrl:[DataProcessing shareSingle].freval_data_host url:url];
}

+ (NSString*)fullQuizCommonScriptUrl:(NSString*)url{
    return [self full_BaseUrl:[DataProcessing shareSingle].quiz_common_scripts_host url:url];
}

+ (NSString*)fullBookZipFileUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].book_zip_file_url url:url];
}
+ (NSString*)fullSupportFileUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].support_file_url url:url];
}
+ (NSString*)fullBookCoverImageUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].book_cover_img_url url:url];
}
+ (NSString*)fullBookshelfIconImageUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].bookshelf_icon_img_url url:url];
}
+ (NSString*)fullBannerImageUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].banner_img_url url:url];
}
+ (NSString*)fullAdvert_img_url:(NSString *)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].advert_img_url url:url];
}

+ (NSString*)fullQuizUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].quiz_url url:url];
}

+ (NSString*)fullDuyinUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].wordsDuyin_url url:url];
}

+ (NSString*)fullPeituUrl:(NSString*)url
{
    return [self full_BaseUrl:[DataProcessing shareSingle].wordsPeitu_url url:url];
}
//
+ (NSString*)fullBookLocalHtmlWithBookId:(NSInteger)bookId{
    return [self full_BaseUrl:[DataProcessing shareSingle].booksDirectorLocalUrl url:[NSString stringWithFormat:@"book%@/index.html",@(bookId)]];
}
//
+ (BOOL)isDictOutTime:(NSDate *)dateZ
{
#ifdef __DictOutTime_
    return [[NSDate date] timeIntervalSinceDate:dateZ] >= __DictOutTime_*24*60*60 ;
#endif
    NSUInteger days = [self shareSingle].dictExpiry_Day;
    if ([self shareSingle].dictExpiry_Date != nil) {
        NSComparisonResult ret = [dateZ compare:[self shareSingle].dictExpiry_Date];
        if (ret == NSOrderedAscending) {
            return [[NSDate date] timeIntervalSinceDate:dateZ] >= days*24*60*60;
        }else{
            return YES;
        }
    }else{
        return [[NSDate date] timeIntervalSinceDate:dateZ] >= days*24*60*60;
    }
    return YES;
}

+ (NSString *)tempZipPathForBookID:(NSInteger)bookid urlPath:(NSString *)urlpath
{
    NSString* fileName = [NSString stringWithFormat:@"book%d_%@.zip.tl",(int)bookid,@([urlpath hash])];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].tempDirector];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"tempZipPath:%@",SystemSave);
#endif
    return SystemSave;
}

+ (NSString *)storeZipPathForBookID:(NSInteger)bookid urlPath:(NSString *)urlpath
{
    NSString* fileName = [NSString stringWithFormat:@"book%d_%@.zip",(int)bookid,@([urlpath hash])];
    NSString* zipPath =  [NSString stringWithFormat:@"book%d",(int)bookid];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].zipDirector];
    documentsDirectory = [documentsDirectory stringByAppendingPathComponent:zipPath];
    //
    if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    //
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"ZipPath:%@",SystemSave);
#endif
    return SystemSave;
}

+ (NSString *)storeZipPathForBookID:(NSInteger)bookid
{
    NSString* fileName =  [NSString stringWithFormat:@"book%d",(int)bookid];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].zipDirector];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"ZipPath:%@",SystemSave);
#endif
    return SystemSave;
}

+ (NSString*)bookPathForBookID:(NSInteger)bookid
{
    if ([self shareSingle].isOutPath && [self shareSingle].outPath) {
        return [self shareSingle].outPath;
    }
    NSString* fileName = [NSString stringWithFormat:@"book%d",(int)bookid];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].booksDirector];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"Bookpath:%@",SystemSave);
#endif
    return SystemSave;
}

+ (NSString *)bookPathForBookID:(NSInteger)bookid subDir:(NSString *)name
{
    NSString *documentsDirectory = [self bookPathForBookID:bookid];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:name];
#if __Debug_DataProcessing
    NSLog(@"Bookpath subDir:%@",SystemSave);
#endif
    return SystemSave;
}

+ (NSString *)wordDictPathForBookID:(NSInteger)bookid
{
    NSString* fileName = [NSString stringWithFormat:@"book%d_dict.telen",(int)bookid];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].wordsDictDirector];
    //
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"dicPath:%@",SystemSave);
#endif
    return SystemSave;
}

+ (NSString *)wordDictSoundPath
{
    NSString *SystemSave = [NSString stringWithString:[self shareSingle].wordsDictDirectorSound];
    //
    return SystemSave;
#if __Debug_DataProcessing
    NSLog(@"dicSoundPath:%@",SystemSave);
#endif
    return SystemSave;
}

+ (BOOL)unZipBookZipPath:(NSString *)path forBookid:(NSInteger)bookid
{
    if (![path.lastPathComponent hasSuffix:@".zip"]) {
        return NO;
    }
    //
    NSString* uzipPath = [DataProcessing bookPathForBookID:bookid];
    JRZipArchive* zp = [[JRZipArchive alloc] init];
    [zp UnzipOpenFile:path];
    BOOL result = [zp UnzipFileTo:uzipPath overWrite:YES];
    if (!result) {
        NSLog(@"解压失败bookid:%d path:%@",(int)bookid,path);
    }

    else
    {
#if __Debug_DataProcessing
        NSLog(@"解压成功 bookid:%d path:%@",bookid,path);
#endif
    }

    [zp UnzipCloseFile];
    return result;
}

+ (BOOL)unZipQuizBookZipPath:(NSString*)path forBookOriginal:(NSInteger)OriginalId {
    if (![path.lastPathComponent hasSuffix:@".zip"]) {
        return NO;
    }
    //
    NSString *uzipPath = [DataProcessing quizDataPathForBookOriginalID:OriginalId];
    JRZipArchive* zp = [[JRZipArchive alloc] init];
    [zp UnzipOpenFile:path];
    BOOL result = [zp UnzipFileTo:uzipPath overWrite:YES];
    if (!result) {
        NSLog(@"解压失败quiz_originalid:%d path:%@",(int)OriginalId,path);
    }
    else
    {
#if __Debug_DataProcessing
        NSLog(@"解压成功quiz_quiz_originalid:%d path:%@",OriginalId,path);
#endif
    }
    
    [zp UnzipCloseFile];
    return result;
}

+ (NSDictionary*)getBookJsonInfo:(NSInteger)bookId
{
    NSDictionary* dic = nil;
    if (bookId > 0) {
        NSString* path = [DataProcessing bookPathForBookID:bookId];
        path  = [path stringByAppendingPathComponent:@"book.json"];
        NSData* data = [[NSData alloc] initWithContentsOfFile:path];
        if (data) {
            dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        }
    }
#if __Debug_BooksFileReading
    NSLog(@"bookid:%d bookjon: %@",bookId,dic);
#endif
    return dic;
}

+ (NSDictionary*)getEvaluatingJsonInfo:(NSInteger)bookId{
    NSDictionary* dic = nil;
    if (bookId > 0) {
        NSString* path = [DataProcessing bookPathForBookID:bookId];
        path  = [path stringByAppendingPathComponent:@"asr_engine.json"];
        NSData* data = [[NSData alloc] initWithContentsOfFile:path];
        if (data) {
            dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        }
    }
#if __Debug_BooksFileReading
    NSLog(@"bookid:%d bookjon: %@",bookId,dic);
#endif
    return dic;
}

//删除quiz数据
+ (void)deleteQuizBookFiles:(NSInteger)originId bookId:(NSInteger)bookid{
    NSString *quizpath = [self quizDataPathForBookOriginalID:originId];
    NSString* zipPath = [self storeZipPathForBookID:bookid];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:quizpath error:nil];
    if (error) {
        NSLog(@"%@",error);
    }
    error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];
    if (error) {
        NSLog(@"%@",error);
    }
}

+ (void)deleteBookFiles:(NSInteger)bookid
{
    NSString* bookpath = [self bookPathForBookID:bookid];
    NSString* zipPath = [self storeZipPathForBookID:bookid];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:bookpath error:nil];
    if (error) {
        NSLog(@"%@",error);
    }
    error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];
    if (error) {
        NSLog(@"%@",error);
    }
}
//删除一组书
+ (void)deleteBooksFilesWithBookIDArr:(NSArray*)bookIdArr{
    for (NSNumber* bookId in bookIdArr) {
        [self deleteBookFiles:[bookId integerValue]];
    }
}

+ (void)deleteBookZips:(NSInteger)bookid
{
    NSString* zipPath = [self storeZipPathForBookID:bookid];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:zipPath error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
}

- (BOOL)isChineseForLocalSystem
{
    return isForChinese;
}

- (NSString*)language
{
    if([DataProcessing shareSingle].isChineseForLocalSystem){
        return @"zh";
    }else{
        return @"en";
    }
}

- (void)dealloc
{
    [thread cancel],thread = nil;
}

-(NSString*) machineName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* deviceString = [NSString stringWithCString:systemInfo.machine
                                                encoding:NSUTF8StringEncoding];
    NSString* deviceModel = [[UIDevice currentDevice] model];
    if ([deviceString hasPrefix:deviceModel]) {
        return deviceString;
    }
    return deviceModel;
}

- (instancetype)init
{
    if (self = [super init]) {
        if ([@"en" isEqualToString:NSLocalizedString(@"language", nil)]) {
            isForChinese = NO;
        }else{
            isForChinese = YES;
        }
        self.soundPlayRatio_fast = __SoundFastRatio_;
        self.soundPlayRatio_slower = __SoundSlowerRatio_;
        mSoundConvertQue = [[NSMutableArray alloc] initWithCapacity:0];
        soundConvertDelegateArr = [[NSMutableArray alloc] initWithCapacity:0];
        //
        NSString* tlDevice = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleTLDevice"];
        if (tlDevice.length <= 0) {
            tlDevice = [self machineName];
        }
        if (tlDevice) {
            if ([tlDevice hasPrefix:@"iPhone"] || [tlDevice hasPrefix:@"iPod"]) {
                _deviceType = DevicesTypes_iPhone;
            }
            if ([tlDevice hasPrefix:@"iPad"]) {
                _deviceType = DevicesTypes_iPad;
            }
        }
        //
        NSString* os_ver = [UIDevice currentDevice].systemVersion;
        if ([os_ver floatValue] < 8) {
            _canWindowRotation = NO;
        }else{
            _canWindowRotation = YES;
        }
        //NSLog(@"%@ %d",tlDevice,self.deviceType);
        //
        // Init the disk cache
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        self.tempDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"zipBooksCache"];
        self.zipDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"zipBooks"];
        self.talksZipDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"zipTalks"];
        self.booksDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Books"];
        self.talksDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Talks"];
        self.talksVideoDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"talksVideo"];
        self.wordsDictDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"wordsDict"];
        self.wordsDictDirectorSound = [self.wordsDictDirector stringByAppendingPathComponent:@"Sound"];
        self.supportFilesDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"supportFiles"];
        self.indexHtmlDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"flowLayoutHtmlZip"];
        self.quizDirector = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Quiz"];
        self.courseDirector = [self.quizDirector stringByAppendingPathComponent:@"app/index/data"];
        BOOL isDirectory = NO;
        BOOL isFileExists = NO;
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.talksZipDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"talkZipDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.talksZipDirector error:nil];
        }
        if (!isDirectory || !isFileExists) {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.talksZipDirector withIntermediateDirectories:YES attributes:nil error:NULL];
        }
        
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.talksDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"talksDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.talksDirector error:nil];
        }
        if (!isDirectory || !isFileExists) {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.talksDirector withIntermediateDirectories:YES attributes:nil error:NULL];
        }
        
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.talksVideoDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"talksVideoDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.talksVideoDirector error:nil];
        }
        if (!isFileExists || !isDirectory) {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.talksVideoDirector withIntermediateDirectories:YES attributes:nil error:NULL];
        }
        
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.tempDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"tempDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.tempDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.tempDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.zipDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"zipDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.zipDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.zipDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.booksDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"booksDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.booksDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.booksDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.wordsDictDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"wordsDictDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.wordsDictDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.wordsDictDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.wordsDictDirectorSound isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"wordsDictDirectorSound error");
            [[NSFileManager defaultManager] removeItemAtPath:self.wordsDictDirectorSound error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.wordsDictDirectorSound
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.supportFilesDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"supportFilesDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.supportFilesDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.supportFilesDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.indexHtmlDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"indexHtmlDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.indexHtmlDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.indexHtmlDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //quiz路径
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.quizDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"quizDirector error");
            [[NSFileManager defaultManager] removeItemAtPath:self.quizDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.quizDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        //quiz下course路径
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.courseDirector isDirectory:&isDirectory];
        if (!isDirectory && isFileExists) {
            NSLog(@"quiz/cource Director error");
            [[NSFileManager defaultManager] removeItemAtPath:self.courseDirector error:nil];
        }
        if(!isFileExists || !isDirectory)
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.courseDirector
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        
    }
    return self;
}

+ (NSString *)avatarPathForSelf
{
    UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
    NSString* name = [NSString stringWithFormat:@"selfAvatar_%ld.jpg",(long)uinfo.uid];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:name];
    return imageFilePath;
}

+ (NSString *)avatarRelativePathForSelf_onServer
{
    NSTimeInterval time  = [[NSDate date] timeIntervalSince1970];
    UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
    NSString* path = [NSString stringWithFormat:@"/avatar/avatar_uid_%ld_%@.jpg",(long)uinfo.uid,@(time)];
    return path;
}

+ (NSArray *)getNumbersFromString:(NSString *)str
{
    NSArray* arr= nil;
    nullToNil(str);
    if (str) {
        NSMutableArray* marr = [[NSMutableArray alloc] initWithCapacity:0];
        NSArray* subStrs = [str componentsSeparatedByString:@","];
        for (NSString* numstr in subStrs) {
            if(numstr.length==0)continue;
            NSNumber* num = [NSNumber numberWithInteger:[numstr integerValue]];
            [marr addObject:num];
        }
        arr = marr;
    }
    return arr;
}

+ (NSString *)getFastSoudFilePathFromPath:(NSString *)ose
{
    NSString* fileName = [[ose lastPathComponent] stringByDeletingPathExtension];
    NSString* path = [ose stringByDeletingLastPathComponent];
    NSString* fastFile = [NSString stringWithFormat:@"%@_f%d.mp3",fileName,(int)[DataProcessing shareSingle].soundPlayRatio_fast];
    //
    fastFile = [path stringByAppendingPathComponent:fastFile];
    return fastFile;
}

+ (NSString *)getSlowerSoudFilePathFromPath:(NSString *)ose
{
    NSString* fileName = [[ose lastPathComponent] stringByDeletingPathExtension];
    NSString* path = [ose stringByDeletingLastPathComponent];
    NSString* slowerFile = [NSString stringWithFormat:@"%@_s%d.mp3",fileName,(int)[DataProcessing shareSingle].soundPlayRatio_slower];
    //
    slowerFile = [path stringByAppendingPathComponent:slowerFile];
    return slowerFile;
}

+ (NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (NSString*)getFeiBoLaQiString:(NSString*)code
{
    NSArray* farr = @[@1,@1,@2,@3,@5,@8,@13,@21];//费波拉契线序列 8位指的是(1,1,2,3,5,8,13,21)
    if (code.length < 21) {
        NSLog(@"加密code 错误");
        return nil;
    }
    NSMutableString* str = [[NSMutableString alloc] initWithCapacity:farr.count];
    for (NSNumber* index in farr) {
        int i = [index intValue];
        [str appendString:[code substringWithRange:NSMakeRange(i, 1)]];
    }
    return str;
}

+ (NSDictionary *)getSaltInfo
{

    NSString *currentTime = [[NSString alloc] initWithFormat:@"%0.f",[[NSDate date] timeIntervalSince1970]*1000];

    //currentTime = @"1426571779";
    NSString * code = [self md5:[__salt stringByAppendingString:currentTime]];
    code = [self getFeiBoLaQiString:code];
    code = [NSString stringWithFormat:@"%@%@%@",code,__salt,currentTime];
    code = [self md5:code];
    code = [self getFeiBoLaQiString:code];
    return [NSDictionary dictionaryWithObjectsAndKeys:currentTime,@"timestamp",code,@"sig", nil];
}

+ (NSString*)changForEncode:(NSString*)code
{
    while ([[code substringWithRange:NSMakeRange(code.length-1, 1)] isEqualToString:@"="]) {
        code = [code substringToIndex:code.length-1];
    }
    NSMutableString* str = [[NSMutableString alloc] initWithCapacity:code.length];
    for (int i=0; i<code.length;i++) {
        NSString* c = [code substringWithRange:NSMakeRange(i, 1)];
        if ([c isEqualToString:@"+"]) {
            c = @"-";
        }else if([c isEqualToString:@"/"]){
            c = @"_";
        }
        [str appendString:c];
    }
    return str;
}

+ (NSString*)passWord_enCode:(NSString *)code
{
    while (code.length < 4) {
        code = [code stringByAppendingString:@"x"];
    }
    code = [code base64EncodedString];
    code = [self changForEncode:code];
    NSString* c4 = [code substringWithRange:NSMakeRange(0, 4)];
    code = [code substringFromIndex:4];
    code = [code stringByAppendingString:c4];
    code = [code base64EncodedString];
    code = [self changForEncode:code];
    return code;
}

+ (NSString*)changForDecode:(NSString*)code
{
    NSMutableString* str = [[NSMutableString alloc] initWithCapacity:code.length];
    for (int i=0; i<code.length;i++) {
        NSString* c = [code substringWithRange:NSMakeRange(i, 1)];
        if ([c isEqualToString:@"-"]) {
            c = @"+";
        }else if([c isEqualToString:@"_"]){
            c = @"/";
        }
        [str appendString:c];
    }
    NSInteger x = code.length%4;
    if (x>0) x = 4 - x;
    for (int i=0; i<x; i++) {
        [str appendString:@"="];
    }
    return str;
}

+ (NSString*)passWord_deCode:(NSString *)code
{
    code = [self changForDecode:code];
    code = [code base64DecodedString];
    NSString* c4 = [code substringFromIndex:code.length-4];
    code = [code substringToIndex:code.length-4];
    code = [c4 stringByAppendingString:code];
    code = [self changForDecode:code];
    code = [code base64DecodedString];
    return code;
}

- (void)regSoundDelegate:(id<DataProcessingAsyncSoudConvertFilesDelegate>)delegate
{
    NSValue* value = [NSValue valueWithNonretainedObject:delegate];
    [soundConvertDelegateArr addObject:value];
}

- (void)unRegSoundDelegate:(id<DataProcessingAsyncSoudConvertFilesDelegate>)delegate
{
    NSArray* arr = [NSArray arrayWithArray:soundConvertDelegateArr];
    for (NSValue* value in arr) {
        if([value nonretainedObjectValue] == delegate){
            [soundConvertDelegateArr removeObject:value];
        }
    }
}

#ifndef WHY_PJ
- (void)soundFilesConvert_AsyncThread
{
    NSString* ose = nil;
    NSString* outFile_end = nil;
    NSString* outFile_wav = nil;
    NSInteger speedRatio = 0;
    NSDictionary* dict = nil;
//    @synchronized(self){
        if (mSoundConvertQue.count > 0) {
            dict = [mSoundConvertQue firstObject];
            ose = [dict objectForKey:@"ose"];
            outFile_end = [dict objectForKey:@"outFile"];
            speedRatio = [[dict objectForKey:@"speedRatio"] integerValue];
            outFile_wav = outFile_end.stringByDeletingPathExtension;
            outFile_wav = [NSString stringWithFormat:@"%@.wav",outFile_wav];
        }else{
            thread = nil;
            return;
        }
//    }
    NSString *sOutFolder = [ose stringByDeletingLastPathComponent];
//    if (![[NSFileManager defaultManager] fileExistsAtPath:outFile]) {
        // to stretch
        CKLSoundStretch *m = [[CKLSoundStretch alloc] initWithInFile:ose andOutFile:outFile_wav];
        if (m == nil){
            for (NSValue* value in soundConvertDelegateArr) {
                id<DataProcessingAsyncSoudConvertFilesDelegate> _delegateSoundConvert= [value nonretainedObjectValue];
                if (_delegateSoundConvert &&[_delegateSoundConvert respondsToSelector:@selector(DataProcessing_soudFilesAsyncConvertFailed:toFiles:)]) {
                    [_delegateSoundConvert DataProcessing_soudFilesAsyncConvertFailed:ose toFiles:outFile_end];
                }
            }
            [self soundFilesConvert_AsyncThread];
            return;
        }
        m.strTmpFolder = sOutFolder;
        [m makeSpeechInWaveFasterOrSlower:speedRatio];
//    }
    //转为压缩的Mp3
    if([TLConvertWavToMp3 ConvertWavFile:outFile_wav toMp3File:[NSString stringWithFormat:@"%@.tmp",outFile_end] progress:nil])
    {
        [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@.tmp",outFile_end] toPath:outFile_end error:nil];
        [[NSFileManager defaultManager] removeItemAtPath:outFile_wav error:nil];
        //
        if(soundConvertDelegateArr && soundConvertDelegateArr.count > 0)for (NSValue* value in soundConvertDelegateArr) {
            id<DataProcessingAsyncSoudConvertFilesDelegate> _delegateSoundConvert= [value nonretainedObjectValue];
            if (_delegateSoundConvert && [_delegateSoundConvert respondsToSelector:@selector(DataProcessing_soudFilesAsyncConvertSuccess:toFiles:)]) {
                [_delegateSoundConvert DataProcessing_soudFilesAsyncConvertSuccess:ose toFiles:outFile_end];
            }
        }
    }
    
    //sleep(1);
    thread = nil;
    [self removeSoundFilesFromConvertQue:dict];
}

- (void)startSoundConvert
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(startSoundConvert) withObject:nil waitUntilDone:NO];
        return;
    }
    if(!thread){
        thread = [[NSThread alloc] initWithTarget:self selector:@selector(soundFilesConvert_AsyncThread) object:nil];
        thread.threadPriority = 0.01; // 设置线程的优先级(0.0 - 1.0，1.0最高级)
        [thread start];
    }
}

- (void)removeSoundFilesFromConvertQue:(NSDictionary*)dict
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(removeSoundFilesFromConvertQue:) withObject:dict waitUntilDone:NO];
        return;
    }
    [mSoundConvertQue removeObject:dict];
    if(mSoundConvertQue.count > 0){
        [self startSoundConvert];
    }
}

- (void)addSoundFilesToConvertQue:(NSDictionary*)dict
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(addSoundFilesToConvertQue:) withObject:dict waitUntilDone:NO];
        return;
    }
    NSString* outFile = [dict objectForKey:@"outFile"];
    NSArray* arr = [NSArray arrayWithArray:mSoundConvertQue];
    for (NSDictionary* dic in arr) {
        if ([outFile isEqual:[dic objectForKey:@"outFile"]]) {
            [mSoundConvertQue removeObject:dic];
            break;
        }
    }
    [mSoundConvertQue insertObject:dict atIndex:0];
    [self startSoundConvert];
}

- (void)soundFilesAsyncConvert:(NSString *)ose toFiles:(NSString *)outFile speedRatio:(NSInteger)speedRatio
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:outFile]) {
        return;
    }
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:ose,@"ose",outFile,@"outFile",[NSNumber numberWithInteger:speedRatio],@"speedRatio",nil];
    [self addSoundFilesToConvertQue:dict];
}
#endif

+ (NSArray *)getDirArrForQuizBooks {
    return @[[DataProcessing shareSingle].courseDirector];
}
+ (NSArray *)getDirArrForBooks
{
    return @[[DataProcessing shareSingle].booksDirector];
}
+ (NSArray *)getDirArrForTalks
{
    return @[[DataProcessing shareSingle].talksDirector,
             [DataProcessing shareSingle].talksVideoDirector,
             [DataProcessing talkInterviewViewSavePath].path
             ];
}
+ (NSArray *)getAudioDirArr {
    return @[];
}

+ (void)cleanDirArr:(NSArray *)pathArr
{
    for (NSString* path in pathArr) {
        if([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
        //åå
        if(![[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            NSURL* url = [NSURL fileURLWithPath:path];
            [[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nil];
            [url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
        }
    }
}


//获取转存talkZip的地址
+ (NSString*)storeTalkZipPathForOriginalID:(NSInteger)originalid{
    NSString* fileName =  [NSString stringWithFormat:@"%d.zip",(int)originalid];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].talksZipDirector];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"ZipPath:%@",SystemSave);
#endif
    return SystemSave;
}

//获取talk Zip解压后的地址
+ (NSString*)talkPathForOriginalID:(NSInteger)originalid{
    NSString* fileName = [NSString stringWithFormat:@"%d",(int)originalid];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].talksDirector];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"Bookpath:%@",SystemSave);
#endif
    return SystemSave;
}
//Talk视频文件的路径地址
+ (NSString*)talkVideoPath{
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].talksVideoDirector];
    
#if __Debug_DataProcessing
    NSLog(@"Bookpath:%@",SystemSave);
#endif
    return documentsDirectory;
}
//删除解压后文件 及相关目录
+ (void)deleteTalkFiles:(NSInteger)originalid{
    NSString* talkPath = [self talkPathForOriginalID:originalid];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:talkPath error:nil];
    if (error) {
        NSLog(@"%@",error);
    }
}
//仅仅删除zip包
+ (void)deleteTalkZips:(NSInteger)originalid{
    NSString* zipPath = [self storeTalkZipPathForOriginalID:originalid];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:zipPath error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
}
//按照文件名删除视频文件
+ (void)deleteTalkVideoFiles:(NSString *)videoName{
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].talksVideoDirector];
    NSString *videoPath = [documentsDirectory stringByAppendingPathComponent:videoName];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:videoPath error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
}
//解压
+ (BOOL)unZipTalkZipPath:(NSString *)path forOriginalID:(NSInteger)originalid{
    if (![path.lastPathComponent hasSuffix:@".zip"]) {
        return NO;
    }
    //
    NSString* uzipPath = [DataProcessing talkPathForOriginalID:originalid];
    JRZipArchive* zp = [[JRZipArchive alloc] init];
    [zp UnzipOpenFile:path];
    BOOL result = [zp UnzipFileTo:uzipPath overWrite:YES];
    if (!result) {
        NSLog(@"解压失败originalid:%d path:%@",(int)originalid,path);
    }
    
    else
    {
#if __Debug_DataProcessing
        NSLog(@"解压成功 bookid:%d path:%@",originalid,path);
#endif
    }
    
    [zp UnzipCloseFile];
    return result;
}

//按路径解压
+ (BOOL)unZipFromZipFilePath:(NSString*)zipPath ToUnZipPath:(NSString*)UnzipPath{
    if (![zipPath.lastPathComponent hasSuffix:@".zip"]) {
        return NO;
    }
    //
    JRZipArchive* zp = [[JRZipArchive alloc] init];
    [zp UnzipOpenFile:zipPath];
    BOOL result = [zp UnzipFileTo:UnzipPath overWrite:YES];
    if (!result) {
        NSLog(@"解压index.html失败");
    }
    else
    {
#if __Debug_DataProcessing
        NSLog(@"解压index.html成功");
#endif
    }
    
    [zp UnzipCloseFile];
    return result;
}


//读取Talk根目录信息
+ (NSDictionary*)getTalkJsonInfo:(NSInteger)originalid{
    NSDictionary* dic = nil;
    if (originalid > 0) {
        NSString* path = [DataProcessing talkPathForOriginalID:originalid];
        path  = [path stringByAppendingPathComponent:@"extend.json"];
        NSData* data = [[NSData alloc] initWithContentsOfFile:path];
        if (data) {
            dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        }
    }

    return dic;
}

+ (NSURL *)talkInterviewViewSavePath
{
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                             inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;
    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }
    if (appSupportDir) {
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
    }
    return appDirectory;
}
//TalkInterviewSavePath
+ (NSURL *)talkInterviewViewSavePathForOriginalID:(NSInteger)oid
{
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                             inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;
    
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    
    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }
    if (appSupportDir) {
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        appBundleID = [appBundleID stringByAppendingString:[NSString stringWithFormat:@"/talk_uid_%@/%@",@(uinfo.uid),@(oid)]];
        appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
    }
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:appDirectory.path])
    {
        [[NSFileManager defaultManager] createDirectoryAtURL:appDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        [appDirectory setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
    
    return appDirectory;
}

+ (void)talkInterviewView_Delete_ForOriginalID:(NSInteger)oid
{
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                             inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;
    
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    
    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }
    if (appSupportDir) {
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        appBundleID = [appBundleID stringByAppendingString:[NSString stringWithFormat:@"/talk_uid_%@/%@",@(uinfo.uid),@(oid)]];
        appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
    }
    
    if([[NSFileManager defaultManager] fileExistsAtPath:appDirectory.path])
    {
        [[NSFileManager defaultManager] removeItemAtPath:appDirectory.path error:nil];
    }
}

//quiz
//获取quiz/index/data template.html路径
+ (NSString *)getQuizPublicHtmlPath {
    NSString *dataPath = [[DataProcessing shareSingle].courseDirector stringByDeletingLastPathComponent];
    NSString *htmlStr = [dataPath stringByAppendingPathComponent:@"temStart.html"];
    return htmlStr;
}


//quit/index/data for bookOriginalID
+ (NSString *)quizDataPathForBookOriginalID:(NSInteger)original {
    NSString* fileName = [NSString stringWithFormat:@"quiz%d",(int)original];
    NSString *documentsDirectory = [NSString stringWithString:[self shareSingle].courseDirector];
    NSString *SystemSave         = [documentsDirectory stringByAppendingPathComponent:fileName];
#if __Debug_DataProcessing
    NSLog(@"course path:%@",SystemSave);
#endif
    return SystemSave;
}


//获取quiz根目录信息
+ (NSDictionary*)getQuizJsonInfo:(NSInteger)bookId{
    NSDictionary* dic = nil;
    if (bookId > 0) {
        NSString* path = [DataProcessing bookPathForBookID:bookId];
        path  = [path stringByAppendingPathComponent:@"quiz.json"];
        NSData* data = [[NSData alloc] initWithContentsOfFile:path];
        if (data) {
            dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        }
    }
#if __Debug_BooksFileReading
    NSLog(@"bookid:%d quizjson: %@",bookId,dic);
#endif
    return dic;
}

//获取图片
+ (UIImage*)getQuizImageWithFilePath:(NSString*)filePath BookID:(NSInteger)bookId{
    UIImage* image = nil;
    if (bookId > 0) {
        NSString* path = [DataProcessing bookPathForBookID:bookId];
        path  = [path stringByAppendingPathComponent:filePath];
        NSData* data = [[NSData alloc] initWithContentsOfFile:path];
        if (data) {
            image = [UIImage imageWithData:data];
        }
    }
    return image;
}
//获取音频路径
+ (NSString*)getQuizVoiceWithComPath:(NSString*)filePath BookID:(NSInteger)bookId{
    NSString* path = [DataProcessing bookPathForBookID:bookId];
    path  = [path stringByAppendingPathComponent:filePath];
    return path;
}

//
//判断一个字符是否为全角数字
+ (BOOL)isFullWidthNumber:(NSString*)numberStr{
    if ([numberStr isEqualToString:@"１"] || [numberStr isEqualToString:@"２"] ||[numberStr isEqualToString:@"３"]||[numberStr isEqualToString:@"４"] || [numberStr isEqualToString:@"５"] ||[numberStr isEqualToString:@"６"]||[numberStr isEqualToString:@"７"] || [numberStr isEqualToString:@"８"] ||[numberStr isEqualToString:@"９"]) {
        return YES;
    }
    return NO;
}
//
//SDW含有默认头像的方法(imageView)
+(void)SDW_setImageContainDefaultAvatarWithURL:(NSURL*)url View:(UIView*)view Gender:(NSInteger)gender{
    UIImage* defaultAvatar = [UIImage imageNamed:@"defaultAvatar_boy.jpg"];
    if (gender) {//0 男 1女
        defaultAvatar = [UIImage imageNamed:@"defaultAvatar_girl.jpg"];
    }
    if ([view isKindOfClass:[UIImageView class]]) {
        UIImageView* imageView = (UIImageView*)view;
        [imageView JRSD_setImageWithURL:url placeholderImage:defaultAvatar];
    }else if ([view isKindOfClass:[UIButton class]]){
        UIButton* button = (UIButton*)view;
        [button JRSD_setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:defaultAvatar];
    }
}

+ (UIImage *)contentFileImageWithName:(NSString *)imgName type:(NSString *)type {
    if (imgName && type) {
        NSString *imgPath = [[NSBundle mainBundle] pathForResource:imgName ofType:type];
        UIImage *Img = [UIImage imageWithContentsOfFile:imgPath];
        return Img;
    }else {
        return nil;
    }
}

//获取用户底部toolBar
+ (NSArray *)rootToolBarData {
    NSMutableArray *toolBar = [NSMutableArray arrayWithArray:
                               @[
                                 @{@"code" : @"homepage",   //首页
                                   @"color" : @"#FEB010",
                                   @"isDefault" : @(1),
                                   @"menuId" : @(30),
                                   @"model" : @"list",
                                   @"nameEn" : @"Home",
                                   @"nameZh" : @"主页",
                                   @"value" : @""},
                                 
                                 @{@"code" : @"booklib",   //书库
                                   @"color" : @"#817BCF",
                                   @"isDefault" : @(0),
                                   @"menuId" : @(15),
                                   @"model" : @"home",
                                   @"nameEn" : @"Library",
                                   @"nameZh" : @"书库",
                                   @"value" : @""},
                                 
                                 @{@"code" : @"cards",   //故事卡
                                   @"color" : @"#64B200",
                                   @"isDefault" : @(0),
                                   @"menuId" : @(18),
                                   @"model" : @"card",
                                   @"nameEn" : @"Cards",
                                   @"nameZh" : @"故事卡",
                                   @"value" : @""},
                                 //故事卡
                                 @{@"code" : @"me",   //我的
                                   @"color" : @"#F7858D",
                                   @"isDefault" : @(0),
                                   @"menuId" : @(30),
                                   @"model" : @"list",
                                   @"nameEn" : @"Mine",
                                   @"nameZh" : @"我的",
                                   @"value" : @""},]
                               ];
    
    UserInfo *uinfo = [CacheData shareSingle].getUserLoginInfo;
    if (uinfo.s_flag == 1) {        //特殊用户
        [toolBar insertObject:@{@"code" : @"special",   //特殊首页
                                @"color" : @"#EE7A35",
                                @"isDefault" : @(1),
                                @"menuId" : @(27),
                                @"model" : @"list",
                                @"nameEn" : @"Main",
                                @"nameZh" : @"首页",
                                @"value" : @""}
                      atIndex:0];
        [toolBar replaceObjectAtIndex:1 withObject:@{@"code" : @"homepage",
                                                     @"color" : @"#FEB010",
                                                     @"isDefault" : @(0),
                                                     @"menuId" : @(30),
                                                     @"model" : @"list",
                                                     @"nameEn" : @"Home",
                                                     @"nameZh" : @"主页",
                                                     @"value" : @""}];
    }
    return toolBar;
}
@end
